package com.jy.api.payservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.jy.api.payReq.TransBaseRequest;
import com.jy.api.payUtil.*;
import lombok.extern.slf4j.Slf4j;


import java.util.*;

@Slf4j
public class CommonService {
	private static final String SIGN_KEY = "sign";

	public static String sign(TransBaseRequest request, String sysPriKey) {
		JSONObject contextJson = JSON.parseObject(JSON.toJSONString(request));
		String signContext = getSignContext(contextJson);
        log.info("签名前内容为：" + signContext);
        String sign = RSA256Utils.sign256(signContext, sysPriKey);
        contextJson.put(SIGN_KEY, sign);
		return JSON.toJSONString(contextJson);
	}

	public static String httpToInvoke(String requestStr, String url) {
		HttpRequestModel requestModel = new HttpRequestModel("嘉联外接码付");
		requestModel.buidHttpPost(url, requestStr, HttpRequestContextType.JSON);
		HttpServiceImpl serviceImpl = new HttpServiceImpl();
		HttpResult httpResult = serviceImpl.execute(requestModel);
		if (null == httpResult) {
			throw new JlpayException(ErrorConstants.NETWORK_TIME_OUT, "网络超时");
		}
		return httpResult.getResult();
	}

	public static void checkSign(String responseStr, String jlPubKey) {
		JSONObject contextJson = JSON.parseObject(responseStr);
		String signContext = getSignContext(contextJson);
		log.info("验签前内容为：" + signContext);
		String sign = contextJson.getString(SIGN_KEY);
		boolean flag = RSA256Utils.verify256(signContext, jlPubKey, sign);
		if (!flag) {
			throw new JlpayException(ErrorConstants.VALIDATE_ERROR_1, "验签不通过");
		}
	}

	private static String getSignContext(JSONObject contextJson) {
		List<String> keys =  new ArrayList<>(contextJson.keySet());
	    Collections.sort(keys);
	    Map<String, Object> treeMap = new TreeMap<>();
        for(String key : keys){
            if(!SIGN_KEY.equals(key)){
                treeMap.put(key, contextJson.get(key));
            }
        }
        return JSON.toJSONString(treeMap);
	}
	
}
